﻿// 文件名：编程练习
// 创建时间：2021/6/22/星期二 14:40:45

#include <iostream>
using namespace std;

//编程练习1
double harmonicMean(double a, double b);
void practice1()
{
	double a;
	double b;
	double mean;
	cout << "请输入两个数（输入0退出）：";
	while (cin >> a >> b)
	{
		if (a == 0.0 || b == 0.0)
		{
			return;
		}
		mean = harmonicMean(a, b);
		cout << "a = " << a << ",b = " << b << ":调和平均数 = " << mean << endl;
	}
	cout << "Bad input\n";
}
double harmonicMean(double a, double b)
{
	return 2 * a*b / (a + b);
}

//编程练习2
int setValue(double* arr);
void showValue(const double* arr, int len);
void ave(double* arr, int len);
const int MAX = 10;
void practice2()
{
	double arr[MAX];
	int len = setValue(arr);
	cout << "数组长度为： " << len << endl;
	showValue(arr, len);
	ave(arr, len);
}
void showValue(const double* arr, int len)
{
	if (len == 0)
	{
		cout << "数组为空\n";
	}
	else
	{
		for (int i = 0; i < len; i++)
		{
			cout << "arr[" << i << "] = " << arr[i] << '\t';
		}
		cout << "\n";
	}
	
}
void ave(double* arr, int len)
{
	if (len > 0)
	{
		double sum = 0.0;
		for (int i = 0; i < len; i++)
		{
			sum += arr[i];
		}
		cout << "平均分数为： " << sum / len << endl;
	}
}
int setValue(double* arr)
{
	double temp;
	cout << "请输入最多10个成绩：(q to quit)\n";
	int i;
	for (i = 0; i < MAX; i++)
	{
		cout << "成绩 #" << i + 1 << " : ";
		cin >> temp;
		if (!cin)
		{
			cin.clear();
			if (cin.get() == 'q')
			{
				break;
			}
			while (cin.get() != '\n')
			{
				continue;
			}
			cout << "Bad input\n";
			break;
		}
		else if (temp < 0)
		{
			break;
		}
		arr[i] = temp;
	}
	return i;
}

//编程练习5
int recursive(int n);
void practice5()
{
	int n;
	cout << "计算阶乘的函数\n";
	cout << "请输入阶乘数：";
	cin >> n;
	while (cin)
	{
		int result = recursive(n);
		cout << "阶乘结果为： " << result << endl;
		cout << "请输入阶乘数：";
		cin >> n;
	}
	cout << "Done\n";
}
int recursive(int n)
{
	if (n == 0)
	{
		return 1;
	}
	int result = n * recursive(n - 1);
	return result;
}

int main()
{

	//编程练习1
	//practice1();

	//编程练习2
	//practice2();

	//编程练习5
	practice5();


	system("pause");
	return 0;
}